/**
 * 项目工时统计组件
 */

'use client';

import React, { useState, useMemo } from 'react';
import {
  Card,
  Table,
  Tag,
  Space,
  Button,
  Progress,
  Typography,
  Modal,
  Descriptions,
  List,
  Avatar,
  Tooltip,
  Input,
  Select,
} from 'antd';
import {
  EyeOutlined,
  UserOutlined,
  SearchOutlined,
  TeamOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import type { Workload } from '../types/workload';
import type { WorkloadStatistics } from '../hooks/useWorkloads';

const { Text, Title } = Typography;
const { Option } = Select;

interface ProjectWorkloadStatsProps {
  workloads: Workload[];
  statistics: WorkloadStatistics;
  loading?: boolean;
  dateRange?: [dayjs.Dayjs, dayjs.Dayjs] | null;
}

interface ProjectStatDetail {
  projectId: string;
  projectName: string;
  totalDuration: number;
  percentage: number;
  memberCount: number;
  recordCount: number;
  members: Array<{
    userId: string;
    userName: string;
    duration: number;
    recordCount: number;
  }>;
  workloads: Workload[];
}

export default function ProjectWorkloadStats({
  workloads,
  statistics,
  loading = false,
  dateRange,
}: ProjectWorkloadStatsProps) {
  const [selectedProject, setSelectedProject] = useState<ProjectStatDetail | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [sortBy, setSortBy] = useState<'duration' | 'members' | 'records'>('duration');

  // 计算详细的项目统计数据
  const projectDetails = useMemo((): ProjectStatDetail[] => {
    const projectMap = new Map<string, ProjectStatDetail>();

    workloads.forEach(workload => {
      const projectId = workload.principal.id;
      const projectName = workload.principal.title || '未知项目';

      if (!projectMap.has(projectId)) {
        projectMap.set(projectId, {
          projectId,
          projectName,
          totalDuration: 0,
          percentage: 0,
          memberCount: 0,
          recordCount: 0,
          members: [],
          workloads: [],
        });
      }

      const project = projectMap.get(projectId)!;
      project.totalDuration += workload.duration;
      project.recordCount += 1;
      project.workloads.push(workload);

      // 统计成员信息
      const userId = workload.report_by.id;
      const userName = workload.report_by.display_name;
      
      let member = project.members.find(m => m.userId === userId);
      if (!member) {
        member = {
          userId,
          userName,
          duration: 0,
          recordCount: 0,
        };
        project.members.push(member);
      }
      
      member.duration += workload.duration;
      member.recordCount += 1;
    });

    // 计算百分比和成员数量
    const totalDuration = statistics.totalDuration;
    const result = Array.from(projectMap.values()).map(project => ({
      ...project,
      percentage: totalDuration > 0 ? (project.totalDuration / totalDuration) * 100 : 0,
      memberCount: project.members.length,
    }));

    // 排序
    result.sort((a, b) => {
      switch (sortBy) {
        case 'members':
          return b.memberCount - a.memberCount;
        case 'records':
          return b.recordCount - a.recordCount;
        case 'duration':
        default:
          return b.totalDuration - a.totalDuration;
      }
    });

    return result;
  }, [workloads, statistics.totalDuration, sortBy]);

  // 过滤项目数据
  const filteredProjects = useMemo(() => {
    if (!searchText) return projectDetails;
    
    return projectDetails.filter(project =>
      project.projectName.toLowerCase().includes(searchText.toLowerCase()) ||
      project.projectId.toLowerCase().includes(searchText.toLowerCase())
    );
  }, [projectDetails, searchText]);

  // 查看项目详情
  const handleViewProject = (project: ProjectStatDetail) => {
    setSelectedProject(project);
    setDetailModalVisible(true);
  };

  // 关闭详情模态框
  const handleDetailModalClose = () => {
    setDetailModalVisible(false);
    setSelectedProject(null);
  };

  // 表格列定义
  const columns: ColumnsType<ProjectStatDetail> = [
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 300,
      render: (text: string, record: ProjectStatDetail) => (
        <div>
          <Text strong>{text}</Text>
          <br />
          <Text type="secondary" style={{ fontSize: '12px' }}>
            ID: {record.projectId}
          </Text>
        </div>
      ),
    },
    {
      title: '总工时',
      dataIndex: 'totalDuration',
      key: 'totalDuration',
      width: 120,
      sorter: (a, b) => a.totalDuration - b.totalDuration,
      render: (duration: number) => (
        <Space direction="vertical" size="small">
          <Text strong style={{ color: '#1890ff' }}>
            {duration.toFixed(1)} 小时
          </Text>
        </Space>
      ),
    },
    {
      title: '工时占比',
      dataIndex: 'percentage',
      key: 'percentage',
      width: 150,
      render: (percentage: number) => (
        <div>
          <Progress
            percent={percentage}
            size="small"
            format={(percent) => `${percent?.toFixed(1)}%`}
          />
        </div>
      ),
    },
    {
      title: '参与人员',
      dataIndex: 'memberCount',
      key: 'memberCount',
      width: 100,
      sorter: (a, b) => a.memberCount - b.memberCount,
      render: (count: number) => (
        <Space>
          <TeamOutlined />
          <Text>{count} 人</Text>
        </Space>
      ),
    },
    {
      title: '工时记录',
      dataIndex: 'recordCount',
      key: 'recordCount',
      width: 100,
      sorter: (a, b) => a.recordCount - b.recordCount,
      render: (count: number) => (
        <Space>
          <ClockCircleOutlined />
          <Text>{count} 条</Text>
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 100,
      render: (_, record: ProjectStatDetail) => (
        <Button
          type="link"
          icon={<EyeOutlined />}
          onClick={() => handleViewProject(record)}
        >
          查看详情
        </Button>
      ),
    },
  ];

  return (
    <>
      <Card
        title={
          <Space>
            <span>项目工时统计</span>
            <Text type="secondary">
              ({filteredProjects.length} 个项目)
            </Text>
          </Space>
        }
        extra={
          <Space>
            <Input
              placeholder="搜索项目名称或ID"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: 200 }}
              allowClear
            />
            <Select
              value={sortBy}
              onChange={setSortBy}
              style={{ width: 120 }}
            >
              <Option value="duration">按工时排序</Option>
              <Option value="members">按人员排序</Option>
              <Option value="records">按记录排序</Option>
            </Select>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={filteredProjects}
          rowKey="projectId"
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
          size="small"
        />
      </Card>

      {/* 项目详情模态框 */}
      <Modal
        title={
          <Space>
            <EyeOutlined />
            <span>项目工时详情</span>
          </Space>
        }
        open={detailModalVisible}
        onCancel={handleDetailModalClose}
        width={900}
        footer={[
          <Button key="close" onClick={handleDetailModalClose}>
            关闭
          </Button>
        ]}
      >
        {selectedProject && (
          <div className="space-y-4">
            {/* 项目基本信息 */}
            <Descriptions column={2} bordered size="small">
              <Descriptions.Item label="项目名称" span={2}>
                <Text strong>{selectedProject.projectName}</Text>
              </Descriptions.Item>
              <Descriptions.Item label="项目ID">
                {selectedProject.projectId}
              </Descriptions.Item>
              <Descriptions.Item label="统计时间">
                {dateRange 
                  ? `${dateRange[0].format('YYYY-MM-DD')} 至 ${dateRange[1].format('YYYY-MM-DD')}`
                  : '全部时间'
                }
              </Descriptions.Item>
              <Descriptions.Item label="总工时">
                <Text strong style={{ color: '#1890ff' }}>
                  {selectedProject.totalDuration.toFixed(1)} 小时
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="工时占比">
                <Text strong style={{ color: '#52c41a' }}>
                  {selectedProject.percentage.toFixed(1)}%
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="参与人员">
                {selectedProject.memberCount} 人
              </Descriptions.Item>
              <Descriptions.Item label="工时记录">
                {selectedProject.recordCount} 条
              </Descriptions.Item>
            </Descriptions>

            {/* 成员工时分布 */}
            <Card title="成员工时分布" size="small">
              <List
                dataSource={selectedProject.members.sort((a, b) => b.duration - a.duration)}
                renderItem={(member) => (
                  <List.Item>
                    <List.Item.Meta
                      avatar={
                        <Avatar size="small" icon={<UserOutlined />}>
                          {member.userName[0]}
                        </Avatar>
                      }
                      title={
                        <Space>
                          <Text>{member.userName}</Text>
                          <Tag color="blue">{member.duration.toFixed(1)} 小时</Tag>
                        </Space>
                      }
                      description={
                        <Space>
                          <Text type="secondary">
                            {member.recordCount} 条记录
                          </Text>
                          <Text type="secondary">
                            占项目工时 {((member.duration / selectedProject.totalDuration) * 100).toFixed(1)}%
                          </Text>
                        </Space>
                      }
                    />
                    <div style={{ width: 200 }}>
                      <Progress
                        percent={(member.duration / selectedProject.totalDuration) * 100}
                        size="small"
                        format={(percent) => `${percent?.toFixed(1)}%`}
                      />
                    </div>
                  </List.Item>
                )}
              />
            </Card>
          </div>
        )}
      </Modal>
    </>
  );
}